package cn.four.hqServer.modules.balance.service.impl;

import cn.four.hqServer.common.entity.HqCardInfo;
import cn.four.hqServer.common.entity.HqUserInfo;
import cn.four.hqServer.common.enums.CardStatusEnum;
import cn.four.hqServer.common.result.Result;
import cn.four.hqServer.modules.balance.mapper.LycCardInfoMapper;
import cn.four.hqServer.modules.balance.service.LycCardInfoService;
import cn.four.hqServer.modules.balance.service.LycUserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author znb
 * @since 2023-02-23
 */
@Service
public class LycCardInfoServiceImpl extends ServiceImpl<LycCardInfoMapper, HqCardInfo> implements LycCardInfoService {


    @Resource
    private LycUserInfoService userInfoService;


    //为了提交
    @Override
    public Result getBalance(String userId) {
        QueryWrapper<HqCardInfo> cardInfoQueryWrapper = new QueryWrapper<>();
        //用户信息
        HqUserInfo userInfo = userInfoService.getUserInfo(userId);

        /**
         *             查询没有注销的银行卡信息
         */
        HqCardInfo cardInfo = this.getOne(cardInfoQueryWrapper.eq("user_id", userInfo.getUserId()).
                ne("state", CardStatusEnum.logout.getCode()));

        if (userInfo != null && cardInfo != null) {

            BigDecimal balance = cardInfo.getBalance();
            cardInfo.setPassword(null);

            /**
             * 确认银行卡状态，如果状态不对，去数据库更改
             */
            UpdateWrapper<HqCardInfo> updateWrapper = new UpdateWrapper<>();

            /**
             * 确认是否透支，给出警示
             */
            if (balance.compareTo(new BigDecimal(0)) == -1) {
                /**
                 * 确认银行卡状态，如果状态不对，去数据库更改
                 */
                if (cardInfo.getState() != CardStatusEnum.overdraft.getCode())
                    this.update(updateWrapper.eq("user_id", userId).set("state", CardStatusEnum.overdraft.getCode()));
                return Result.success(CardStatusEnum.overdraft.getCode(), "你的账户已透支", cardInfo);
            }
            /**
             * 正常或冻结状态
             */
            return Result.success(cardInfo.getState(), "成功", cardInfo);

            /**
             * 注销
             */
        } else {
            return Result.error(CardStatusEnum.logout.getCode(), "账户已经注销，你需要重新绑定");
        }

    }
}
